package com.grandbroad.eim.ui.activities;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.TextureView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.easy.west.westclient.api.base.bean.VodBean;
import com.easy.west.westclient.util.UUIDGenerator;
import com.flyco.tablayout.SlidingTabLayout;
import com.grandbroad.eim.R;
import com.grandbroad.eim.base.BaseActivity;
import com.grandbroad.eim.ui.fragment.vidoe.CommentFragment;
import com.grandbroad.eim.ui.fragment.vidoe.DescribleFragment;
import com.grandbroad.eim.utils.CacheUtils;
import com.grandbroad.eim.utils.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import cn.jzvd.JZDataSource;
import cn.jzvd.JZMediaManager;
import cn.jzvd.JzvdStd;
import cn.jzvd.event.CatScreenEvent;
import pub.devrel.easypermissions.EasyPermissions;

import static com.bumptech.glide.load.resource.bitmap.VideoDecoder.FRAME_OPTION;

/**
 * 视频界面
 */
public class VideoActivity extends BaseActivity

{

    /**
     * 播放器的资源id也在其中
     */
    @BindView(R.id.viewpage_video)
    ViewPager viewpageVideo;
    @BindView(R.id.player)
    JzvdStd player;
    @BindView(R.id.sliding_tab)
    SlidingTabLayout slidingTab;
    private List<Fragment> fragmentList = new ArrayList<>();
    private List<String> tltiles = new ArrayList<>();
    private DescribleFragment describleFragment;
    private CommentFragment commentFragment;
    private VideoViewpagerAdapter viewpagerAdapter;
    private VodBean vodBean;
    private boolean is_first=true;
    private String file_path = Environment.getExternalStorageDirectory()+"/MoleFile/camera/";
    //事件uuid
    private String uuid = UUIDGenerator.getUUID();
    @Override
    protected void initview() {
        //播放器准备
        initpalyer();
        initsession();
    }

    private void initsession() {

    }

    /**
     * 请求文件储存权限和截屏
     */
    public void requstpremisson() {
        if (!EasyPermissions.hasPermissions(this,Manifest.permission.WRITE_EXTERNAL_STORAGE))
        {
            EasyPermissions.requestPermissions(this,"请求文件储存的权限",80,Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        else
        {
            //抓取当前视频帧
            loadVideoScreenshot();
        }
    }
    /**
     *  context 上下文
     *  uri 视频地址
     *  imageView 设置image
     *  frameTimeMicros 获取某一时间帧
     */
    public  void loadVideoScreenshot() {
        //跳转一个界面表示截图完成,先暂停
        player.onStatePause();
        Bitmap bitmap = JZMediaManager.textureView.getBitmap();
        //跳转
        CacheUtils.saveBitmap(bitmap);
        Intent intent = new Intent(this, ScreenHotActivity.class);
        /*
        ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(
                this,player.thumbImageView,
               "screen_img");
               */
        startActivity(intent);

        /*
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss",Locale.SIMPLIFIED_CHINESE);
        String time = dateFormat.format(System.currentTimeMillis());
        String fileName = time+"-"+vodBean.getName()+".png";
        //先创建文件夹
        File file = new File(file_path);
        if (!file.exists())
        {
            file.mkdir();
            file.mkdirs();
        }
        String defaultImgPath = file_path + "/"+fileName;
        file = new File(defaultImgPath);
        try {
            file.createNewFile();
            FileOutputStream fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
//            is.close();
            fOut.flush();
            fOut.close();
            ToastUtils.show("保存完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
        */

    }


    private void initpalyer() {
        JZDataSource dataSource = new JZDataSource(vodBean.getUrl());
        dataSource.title = vodBean.getName();
        dataSource.looping=true;
        player.setUuid(uuid);
        player.setUp(dataSource,JzvdStd.SCREEN_WINDOW_NORMAL);

        //封面加载
        x.image().bind(player.thumbImageView,vodBean.getCover_img());
    }


    @Override
    protected void initdata() {
        //获取当前展示的页面数据
        vodBean = (VodBean) getIntent().getExtras().getSerializable("bean");
        initfragment();
        viewpagerAdapter = new VideoViewpagerAdapter(getSupportFragmentManager());
        viewpageVideo.setAdapter(viewpagerAdapter);
        slidingTab.setViewPager(viewpageVideo);
    }

    private void initfragment()
    {
        describleFragment = new DescribleFragment();
        commentFragment = new CommentFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("bean", vodBean);
        describleFragment.setArguments(bundle);
        commentFragment.setArguments(bundle);
        fragmentList.add(describleFragment);
        fragmentList.add(commentFragment);
        tltiles.add("简介");
        tltiles.add("评论");
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_video;
    }




    class VideoViewpagerAdapter extends FragmentPagerAdapter {

        public VideoViewpagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return fragmentList.get(i);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return tltiles.get(position);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //player.onStatePause();

    }

    @Override
    public void onBackPressed() {
        if (player.backPress())
        {
            //全屏返回先退出全屏
            return;
        }
        player.releaseAllVideos();
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //准备播放状态
        //player.changeUiToPreparing();
        if (is_first)
        {
            is_first = false;
        }
        else
        {
            player.changeUiToPreparing();
        }

    }

    @Override
    protected void onDestroy() {
        //释放资源
        player.releaseAllVideos();
        super.onDestroy();

    }

    @Override
    public void finish() {
        //释放资源
        player.releaseAllVideos();
        super.finish();
    }

    /**
     * 接受到播放器截屏事件
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void catScreen(CatScreenEvent eva)
    {
        //确定是在同一个实例化的页面下
        //if (eva.getUuid().equals(uuid))
        {
            requstpremisson();
        }

    }
}

